import { isPlainObject } from 'lodash';
import secret from '@/utils/secret';
import encryptUtil from '@/utils/encrypt';

/** 是否处于开发环境 */
const isDevelopmentEnv = () => process.env.NODE_ENV === 'development';

/** 加秘 */
const encrypt = text => encryptUtil.encrypt(text, secret);

/** 解秘 */
const decrypt = text => encryptUtil.decrypt(text, secret);

const defaultNamespace = '';

const getFullKey = (namespace, key) => (namespace !== undefined ? `${namespace ? `${namespace}.` : ''}${key}` : key);

const sessionStorageUtil = {
    setItem(key, value, namespace = defaultNamespace) {
        const beforeStoreValue = isPlainObject(value) || Array.isArray(value) ? JSON.stringify(value) : value;
        const newValue = isDevelopmentEnv() ? beforeStoreValue : encrypt(beforeStoreValue);
        sessionStorage.setItem(getFullKey(namespace, key), newValue);
    },

    getItem(key, namespace = defaultNamespace) {
        const itemValueInSession = sessionStorage.getItem(getFullKey(namespace, key));
        const readableValue = isDevelopmentEnv() ? itemValueInSession : decrypt(itemValueInSession);
        let parsedValue = readableValue;
        try {
            parsedValue = JSON.parse(readableValue);
            // eslint-disable-next-line no-empty
        } finally {
        }

        return parsedValue;
    },

    removeItem(key, namespace = defaultNamespace) {
        sessionStorage.removeItem(getFullKey(namespace, key));
    },

    /**
     * 删除namespace相同的一组值
     * @param namespace
     */
    removeByNamespace(namespace) {
        Object.keys(sessionStorage).forEach(key => {
            if (key.startsWith(`${namespace}.`)) {
                sessionStorageUtil.removeItem(key, '');
            }
        });
    }
};

const FINANCE_NAMESPACE = 'finance';
Object.assign(sessionStorageUtil, {
    setItemInFinance(key, value) {
        sessionStorageUtil.setItem(key, value, FINANCE_NAMESPACE);
    },

    getItemInFinance(key) {
        return sessionStorageUtil.getItem(key, FINANCE_NAMESPACE);
    },

    removeItemInFinance(key) {
        sessionStorageUtil.removeItem(key, FINANCE_NAMESPACE);
    },

    removeAllInFinance() {
        sessionStorageUtil.removeByNamespace(FINANCE_NAMESPACE);
    }
});

export { sessionStorageUtil };
